﻿using ArticleUploadBatch.WinUI.Configs;
using ArticleUploadBatch.WinUI.Services;
using Common.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ArticleUploadBatch.WinUI.UserControls
{
    public partial class UcToutiaoArticleUpload : UserControl
    {
        public UcToutiaoArticleUpload()
        {
            InitializeComponent();
        }

        void writeLineLogToutiao(string str)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    txtLogToutiao.Text += str + "\r\n";
                }));
            }
            else
            {
                txtLogToutiao.Text += str + "\r\n";
            }
            
        }

        private void btnUploadToutiao_Click(object sender, EventArgs e)
        {
            try
            {
                string userName = txtUserName.Text;
                string pwd = txtPwd.Text;
                string ext = combExtension.Text;

                string fileDir = txtDirToutiao.Text;
                if (!Directory.Exists(fileDir)) return;
                //获取所有文章路径
                string[] filePathList = Directory.GetFiles(fileDir, ext);
                if (filePathList.Length == 0)
                {
                    MessageBox.Show("当前目录中没有文章");
                    return;
                }
                Task.Run(() =>
                {
                    ToutiaoArticleService articleService = new ToutiaoArticleService(userName, pwd);
                    articleService.UploadMany(filePathList, writeLineLogToutiao);

                    string sourceDir = txtDirToutiao.Text.Trim();
                    string destDir = Path.Combine(Environment.CurrentDirectory, "已上传/Toutiao");
                    if (cbClearSourceDir.Checked && Directory.Exists(sourceDir))
                    {
                        if (!Directory.Exists(destDir))
                        {
                            Directory.CreateDirectory(destDir);
                        }
                        
                        //Directory.Move(sourceDir, Path.Combine(destDir, Path.GetFileName(sourceDir)));
                        string[] files = Directory.GetFiles(sourceDir);
                        //复制已经上传的文件到已上传目录
                        foreach (string file in files)
                        {
                            string fileName = Path.GetFileName(file);
                            string destFile = Path.Combine(destDir, fileName);
                            File.Copy(file, destFile, true);
                        }
                        //删除原目录
                        Directory.Delete(sourceDir, true);
                        this.Invoke(new Action(() =>
                        {
                            this.lstbFiles.DataSource = null;
                        }));
                    }
                    articleService.Quit();
                    MessageBox.Show("文章已经全部上传完成");
                });
            }
            catch (Exception err)
            {
                Log4Helper.Error(err);
                throw err;
            }
            
            #region 旧方法
            ////string cookies = "passport_csrf_token=e73eb7247b72c50cf8fb8525aa4fafb2; passport_csrf_token_default=e73eb7247b72c50cf8fb8525aa4fafb2; s_v_web_id=verify_li1pwion_XwG0usZG_b9YA_4uPK_8k2L_RU3gyubLV3y4; _ba=BA0.2-20230524-5110e-3tMB9zozwLQSxZjQfFVx; d_ticket=c8e9c1e2ff2fceaa09002a3b402077a644fac; n_mh=4ZPAsLHacJwTtvJyaysKitsreCsb0LhrhfvRYdwbscM; sso_auth_status=03303e391c238bc67e8cc6e4fb591dd1; sso_auth_status_ss=03303e391c238bc67e8cc6e4fb591dd1; sso_uid_tt=b617f3025557af16309989f19e52b216; sso_uid_tt_ss=b617f3025557af16309989f19e52b216; toutiao_sso_user=5181c275b2d91edbddb3f7369ce4fb5e; toutiao_sso_user_ss=5181c275b2d91edbddb3f7369ce4fb5e; sid_ucp_sso_v1=1.0.0-KGJkMWNmOTJiZjcxY2EwOTZmZDg5MmYxYThjODdjNmFiY2UxNDNlMjQKHwjOp_CHgvTGBBCvl7ijBhjPCSAMMOKfiOgFOAJA8QcaAmxmIiA1MTgxYzI3NWIyZDkxZWRiZGRiM2Y3MzY5Y2U0ZmI1ZQ; ssid_ucp_sso_v1=1.0.0-KGJkMWNmOTJiZjcxY2EwOTZmZDg5MmYxYThjODdjNmFiY2UxNDNlMjQKHwjOp_CHgvTGBBCvl7ijBhjPCSAMMOKfiOgFOAJA8QcaAmxmIiA1MTgxYzI3NWIyZDkxZWRiZGRiM2Y3MzY5Y2U0ZmI1ZQ; passport_auth_status=d151625f27ddf9ca6157d1afbc9563d6%2C2afdf20edd3170c50a87c74956d15ea0; passport_auth_status_ss=d151625f27ddf9ca6157d1afbc9563d6%2C2afdf20edd3170c50a87c74956d15ea0; sid_guard=f2d61b706ab7edbebfbe94465cbb185a%7C1684933552%7C5184001%7CSun%2C+23-Jul-2023+13%3A05%3A53+GMT; uid_tt=3c067674a5659d1c15be099916d0fd6c; sid_tt=f2d61b706ab7edbebfbe94465cbb185a; sessionid=f2d61b706ab7edbebfbe94465cbb185a; sid_ucp_v1=1.0.0-KGExMjhkNjViMzEzMGQ4NjVmZGFmMmQzZGMwODgyZGQ5MzU3NWZkMjkKGQjOp_CHgvTGBBCwl7ijBhjPCSAMOAJA8QcaAmxmIiBmMmQ2MWI3MDZhYjdlZGJlYmZiZTk0NDY1Y2JiMTg1YQ; ssid_ucp_v1=1.0.0-KGExMjhkNjViMzEzMGQ4NjVmZGFmMmQzZGMwODgyZGQ5MzU3NWZkMjkKGQjOp_CHgvTGBBCwl7ijBhjPCSAMOAJA8QcaAmxmIiBmMmQ2MWI3MDZhYjdlZGJlYmZiZTk0NDY1Y2JiMTg1YQ; store-region=cn-fj; store-region-src=uid; ttcid=21dbda5cc2664ba99d3c3c2c5dba91b079; tt_webid=7231811825317987898; odin_tt=09b0d9f947d795ecea86f41e4b5cad47d97a97007e0a6f17c7e42744e74b40c86c204c3bd31b1271f75914586eb78154; _S_WIN_WH=1536_722; _S_DPR=1.25; _S_IPAD=0; notRedShot=1; gftoken=ZjJkNjFiNzA2YXwxNjg0OTM3Njg1MzZ8fDAGBgYGBgY; _ga_1Y7TBPV8DE=GS1.1.1685069037.4.1.1685071827.0.0.0; _ga=GA1.1.826492488.1684933884; _ga_QEHZPBE5HH=GS1.1.1685098697.5.1.1685099433.0.0.0; uid_tt_ss=b617f3025557af16309989f19e52b216; sessionid_ss=5181c275b2d91edbddb3f7369ce4fb5e; csrf_session_id=6ac1a5f6821f9f44eb38435589962924; ttwid=1%7CwW844yKlt9XhyPHsNL44XIFR5k08cB-9PK2l14cMg8s%7C1685236077%7C03504f754d3d79d470e21fa0b40908b47ab2b5e84af31c5166a4b3fd4dcbab88; tt_scid=V8uUAwRtoyOyrp3gPj0g0YXRGn.A2MMS707LEUzrF-WYdZZDhu9R.7kaluEAcVRC2874; msToken=D6RHNqL61P2UvxX8h3uq993Ke76KKuoj17a9SsRytTkpYGhCDyOdytKgIXfs6D-9yzDQTlYGlOhIcrkDIREwwJUNoGQJkqPNUAK3wnXFecQ29GWE5CCN2Q==; msToken=SqBOe8uyY_4VVxTiHgzPkybXNcQ5GjzgnciXUTETBp5DC05bJpn_kcS1y1yU1qqSDQ_50GMR6CC8JgqHkxk6YBfU-q3xbzyHN-RE-k3UiNOTuZrCYAb9cw==";
            ////头条发布路径
            //string publishUrl = "https://mp.toutiao.com/profile_v4/graphic/publish";
            //IWebDriver driver = new ChromeDriver();      
            //foreach (string filePath in filePathList)
            //{
            //    driver.Navigate().GoToUrl(publishUrl);
            //    driver.Manage().Timeouts().ImplicitWait=TimeSpan.FromSeconds(10);
            //    Thread.Sleep(2000);

            //    //如果要登陆就先登陆，直达登陆完成
            //    if (driver.Url.Contains("auth/page/login"))
            //    {
            //        //头条登陆
            //        driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__footer > div > ul > li:nth-child(4) > span")).Click();
            //        driver.FindElement(By.Name("normal-input")).SendKeys(userName);//账号
            //        driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-confirm-info > span.web-login-confirm-info__checkbox"))
            //            .Click();//勾选复选框
            //        driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-account-password__password-input-wrapper > div > div > input"))
            //            .SendKeys(pwd);//密码

            //        driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-account-password__button-wrapper > button"))
            //            .Click();//点击登陆

            //        while (true)
            //        {
            //            if (driver.Url.Contains("auth/page/login"))
            //            {
            //                Thread.Sleep(2000);
            //            }
            //            else
            //            {
            //                writeLineLogToutiao("登陆成功：");
            //                break;
            //            }
            //        }
            //    }

            //    //确定是发布文章
            //    if (driver.Url.Contains("graphic/publish"))
            //    {
            //        //单个文章上传
            //        string title = Path.GetFileNameWithoutExtension(filePath);
            //        writeLineLogToutiao("正在上传文章：" + title);
            //        //发布文章
            //        try
            //        {
            //            //是否继续编辑按钮
            //            driver.FindElement(By.CssSelector(".byte-drawer-mask"))
            //           .Click();

            //        }
            //        catch (Exception)
            //        {
            //        }

            //        //try
            //        //{
            //        //    //是否继续编辑按钮
            //        //    driver.FindElement(By.CssSelector("#root > div > div > div.publish-editor > div.publish-draft-tip-wrapper > div > div.draft-content > div"))
            //        //   .Click();

            //        //}
            //        //catch (Exception)
            //        //{
            //        //}
            //        //string filePath = @"E:\工作区-文档\项目2023-正思考-心理-头条号运营\文章\5月28日\硬核理念：高效学习的核心方法！.txt";
            //        if (File.Exists(filePath))
            //        {

            //            driver.FindElement(By.CssSelector("#root > div > div > div.publish-editor > div.publish-editor-title-wrapper > div > div > div.title-wrapper > div > div > div > textarea"))
            //            .SendKeys(title);//输入标题
            //            string content = File.ReadAllText(filePath);
            //            driver.FindElement(By.CssSelector("#root > div > div > div.publish-editor > div.syl-editor-wrap > div > div.ProseMirror"))
            //                .SendKeys(content);//输入文章内容
            //            Thread.Sleep(2000);
            //            //driver.FindElement(By.CssSelector("#root > div > div > div.publish-footer > div > button:nth-child(3)"))
            //            //    .Click();//返回主页
            //            driver.Navigate().GoToUrl("https://mp.toutiao.com/profile_v4/manage/draft");

            //            Thread.Sleep(1000);
            //            writeLineLogToutiao("上传文章成功：" + title);
            //        }
            //    }
            //}
            //writeLineLogToutiao("所有文章上传完成");
            #endregion 旧方法

        }

        private void btnDirToutiao_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog browserDialog = new FolderBrowserDialog();
            browserDialog.SelectedPath = txtDirToutiao.Text;
            if (browserDialog.ShowDialog() == DialogResult.OK)
            {
                txtDirToutiao.Text = browserDialog.SelectedPath;
                refreshFileList();
            }
        }

        private void refreshFileList()
        {
            string ext = combExtension.Text;

            string[] fileList = Directory.GetFiles(txtDirToutiao.Text, ext);
            List<string> fileTitles = new List<string>();
            foreach (var file in fileList)
            {
                fileTitles.Add(Path.GetFileNameWithoutExtension(file));
            }
            lstbFiles.DataSource = fileTitles;
        }

        private void UcToutiaoArticleUpload_Load(object sender, EventArgs e)
        {
            //string[] exts = ConfigurationManager.AppSettings["UploadArticleFileExts"].ToString().Split('|');
            string[] exts = AppConfigXml.GetAppSettingValue("UploadArticleFileExts").ToString().Split('|');
            combExtension.Items.Clear();
            combExtension.Items.AddRange(exts);
            combExtension.SelectedIndex = 0;
            //txtDirToutiao.Text = Environment.CurrentDirectory.ToString();
            if (string.IsNullOrEmpty(txtDirToutiao.Text.Trim()))
            {
                txtDirToutiao.Text = Environment.CurrentDirectory.ToString();
            }
            refreshFileList();
           
        }

    }
}
